<template>
  <div class="app-container">
    <div class="top">
      <div class="site-info">
        <el-tag type="primary" size="medium">{{ siteName }}</el-tag>
        <span style="margin-left: 10px; color: #606266;">模板管理</span>
      </div>

      <div class="search-filter">
        <el-select v-model="listQuery.template_type" placeholder="模板类型" clearable style="width: 150px; margin-right: 10px;" @change="handleSearch">
          <el-option label="落地页模板" value="landing_page" />
          <el-option label="产品页面模板" value="product_page" />
          <el-option label="通用页面模板" value="common" />
          <el-option label="布局模板" value="layout" />
          <el-option label="组件模板" value="component" />
        </el-select>

        <el-input
          v-model="kwInput"
          placeholder="输入模板名称或描述进行筛选"
          class="input-with-select"
          clearable
          @keyup.native.enter="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </el-input>
      </div>

      <el-button
        type="primary"
        class="el-icon-plus add-btn"
        :disabled="listLoading"
        @click="handleAction('create', '添加HTML模板')"
      >添加模板
      </el-button>
    </div>

    <el-table
      v-loading.body="listLoading"
      :data="data"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="handleSort"
    >

      <el-table-column align="center" width="80" prop="id" label="ID" sortable="custom" />

      <el-table-column align="center" label="模板名称" prop="name" min-width="150">
        <template slot-scope="scope">
          <strong>{{ scope.row.name }}</strong>
          <div v-if="scope.row.description" style="font-size: 12px; color: #909399; margin-top: 2px;">
            {{ scope.row.description | truncate(50) }}
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="模板类型" prop="template_type" width="120">
        <template slot-scope="scope">
          <el-tag :type="getTemplateTypeColor(scope.row.template_type)" size="small">
            {{ getTemplateTypeText(scope.row.template_type) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="状态" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_active ? 'success' : 'danger'" size="small">
            {{ scope.row.is_active ? '激活' : '停用' }}
          </el-tag>
          <div v-if="scope.row.is_default" style="margin-top: 2px;">
            <el-tag type="warning" size="mini">默认</el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="AI提示词" width="100">
        <template slot-scope="scope">
          <el-tooltip effect="dark" :content="scope.row.prompt || '无AI提示词'" placement="top">
            <el-tag v-if="scope.row.prompt" type="success" size="mini">
              有提示词
            </el-tag>
            <span v-else style="color: #c0c4cc; font-size: 12px;">无提示词</span>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column align="center" label="模板变量" width="100">
        <template slot-scope="scope">
          <el-tooltip effect="dark" :content="scope.row.variables || '无变量说明'" placement="top">
            <el-tag v-if="scope.row.variables" type="info" size="mini">
              有变量
            </el-tag>
            <span v-else style="color: #c0c4cc; font-size: 12px;">无变量</span>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column align="center" label="创建时间" prop="create_at" width="180" sortable="custom">
        <template slot-scope="scope">
          <span>{{ scope.row.create_at }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="350">
        <template slot-scope="scope">
          <el-button size="mini" type="warning" @click="handlePreviewTemplate(scope.row)">预览</el-button>
          <el-button v-if="!scope.row.is_default" size="mini" type="primary" @click="handleSetDefault(scope.row)">设为默认</el-button>
          <el-button size="mini" type="info" @click="handleAction('edit', scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="total>0"
      background
      :current-page="listQuery.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="listQuery.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <!-- 添加/编辑对话框 -->
    <el-dialog
      class="mt-dialog"
      :title="title"
      :width="width"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="120px">
        <el-form-item v-if="action !== 'delete'" label="模板名称">
          <el-input v-model="temp.name" placeholder="请输入模板名称" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="模板描述">
          <el-input v-model="temp.description" type="textarea" :rows="2" placeholder="请输入模板描述（可选）" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="模板类型">
          <el-select v-model="temp.template_type" placeholder="请选择模板类型" style="width: 100%;">
            <el-option label="落地页模板" value="landing_page" />
            <el-option label="产品页面模板" value="product_page" />
            <el-option label="通用页面模板" value="common" />
            <el-option label="布局模板" value="layout" />
            <el-option label="组件模板" value="component" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="HTML内容">
          <el-input
            v-model="temp.html_content"
            type="textarea"
            :rows="8"
            placeholder="请输入HTML模板内容"
            style="font-family: 'Courier New', monospace;"
          />
          <div style="margin-top: 5px; color: #909399; font-size: 12px;">
            <el-button
              size="mini"
              type="text"
              :disabled="!temp.html_content"
              @click="previewCurrentTemplate"
            >
              预览模板
            </el-button>
          </div>
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="CSS样式">
          <el-input
            v-model="temp.css_content"
            type="textarea"
            :rows="4"
            placeholder="请输入CSS样式（可选）"
            style="font-family: 'Courier New', monospace;"
          />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="JavaScript">
          <el-input
            v-model="temp.js_content"
            type="textarea"
            :rows="4"
            placeholder="请输入JavaScript代码（可选）"
            style="font-family: 'Courier New', monospace;"
          />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="AI生成提示词">
          <el-input
            v-model="temp.prompt"
            type="textarea"
            :rows="4"
            placeholder="请输入AI生成提示词（用于指导AI如何使用该模板生成内容）"
          />
          <div style="margin-top: 5px; color: #909399; font-size: 12px;">
            这个提示词将用于指导AI如何使用该模板生成相应的内容，如页面结构要求、内容风格等
          </div>
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="模板变量">
          <el-input
            v-model="temp.variables"
            type="textarea"
            :rows="3"
            placeholder="请输入模板变量说明（JSON格式，可选）"
            style="font-family: 'Courier New', monospace;"
          />
          <div style="margin-top: 5px; color: #909399; font-size: 12px;">
            格式示例：{"title": "页面标题", "content": "页面内容", "image_url": "图片地址"}
          </div>
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="状态设置">
          <div>
            <el-switch v-model="temp.is_active" active-text="激活" inactive-text="停用" />
          </div>
          <div style="margin-top: 10px;">
            <el-switch v-model="temp.is_default" active-text="设为默认模板" inactive-text="普通模板" />
          </div>
        </el-form-item>

        <div v-if="action === 'delete'" style="text-align: center; font-size: 16px;">
          确认要删除模板 <strong>{{ temp.name }}</strong> 吗？
          <br><br>
          <el-alert title="警告：删除模板后将无法恢复！" type="warning" show-icon />
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 模板预览对话框 -->
    <el-dialog
      title="模板预览"
      :visible.sync="previewVisible"
      width="90%"
      top="5vh"
      :close-on-click-modal="false"
    >
      <div class="preview-container">
        <div class="preview-header">
          <el-tag type="info">{{ previewTemplate.name }}</el-tag>
          <el-tag :type="getTemplateTypeColor(previewTemplate.template_type)" size="small" style="margin-left: 10px;">
            {{ getTemplateTypeText(previewTemplate.template_type) }}
          </el-tag>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-full-screen"
            style="float: right;"
            @click="openFullTemplatePreview"
          >
            全屏预览
          </el-button>
        </div>
        <div class="preview-iframe-container">
          <iframe
            ref="templatePreviewFrame"
            :srcdoc="previewHtml"
            width="100%"
            height="600px"
            frameborder="0"
            sandbox="allow-scripts allow-same-origin"
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 全屏模板预览对话框 -->
    <el-dialog
      title="全屏模板预览"
      :visible.sync="fullPreviewVisible"
      width="95%"
      top="2vh"
      :close-on-click-modal="false"
      custom-class="full-preview-dialog"
    >
      <div class="full-preview-container">
        <iframe
          :srcdoc="previewHtml"
          width="100%"
          height="80vh"
          frameborder="0"
          sandbox="allow-scripts allow-same-origin"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="fullPreviewVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  getHtmlTemplateList,
  createHtmlTemplate,
  updateHtmlTemplate,
  deleteHtmlTemplate
} from '@/api/spider/static_site'

export default {
  name: 'HtmlTemplateIndex',
  filters: {
    truncate(value, length = 50) {
      if (!value) return ''
      if (value.length <= length) return value
      return value.slice(0, length) + '...'
    }
  },
  data() {
    return {
      data: [],
      listLoading: true,
      kwInput: '',
      listQuery: {
        page: 1,
        pageSize: 20,
        site_id: null,
        template_type: ''
      },
      total: 0,
      siteName: '',

      action: null,
      dialogVisible: false,
      title: '',
      temp: {
        name: '',
        description: '',
        template_type: 'common',
        html_content: '',
        css_content: '',
        js_content: '',
        prompt: '',
        variables: '',
        is_active: true,
        is_default: false,
        site: null
      },
      width: '70%',

      // 预览相关
      previewVisible: false,
      fullPreviewVisible: false,
      previewTemplate: {},
      previewHtml: ''
    }
  },
  created() {
    // 从路由参数获取网站ID和名称
    this.listQuery.site_id = this.$route.query.site_id
    this.siteName = this.$route.query.site_name || '未知网站'

    if (!this.listQuery.site_id) {
      this.$message.error('缺少网站ID参数')
      this.$router.go(-1)
      return
    }

    this.getList()
  },
  methods: {
    resetTemp() {
      this.temp = {
        name: '',
        description: '',
        template_type: 'common',
        html_content: '',
        css_content: '',
        js_content: '',
        prompt: '',
        variables: '',
        is_active: true,
        is_default: false,
        site: this.listQuery.site_id
      }
    },
    getList() {
      this.listLoading = true
      const params = {
        page: this.listQuery.page,
        pagesize: this.listQuery.pageSize,
        site_id: this.listQuery.site_id
      }
      if (this.kwInput) {
        params.kw = this.kwInput
      }
      if (this.listQuery.template_type) {
        params.template_type = this.listQuery.template_type
      }

      getHtmlTemplateList(params)
        .then(response => {
          if (response.success) {
            this.data = response.data.data
            this.total = response.data.total
          } else {
            this.$message.error('获取数据失败：' + response.msg)
          }
          this.listLoading = false
        }).catch(err => {
          console.log(err)
          this.$message.error('获取数据失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '70%'
          this.title = '添加HTML模板'
          this.resetTemp()
          this.dialogVisible = true
          break
        case 'edit':
          this.width = '70%'
          this.title = '编辑HTML模板'
          this.temp = Object.assign({}, row)
          this.dialogVisible = true
          break
        case 'delete':
          this.width = '40%'
          this.title = '删除确认'
          this.temp = Object.assign({}, row)
          this.dialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          createHtmlTemplate(_data).then(response => {
            if (response.success) {
              this.dialogVisible = false
              this.getList()
              this.notify('添加成功')
            } else {
              this.$message.error('添加失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('添加失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
        case 'edit':
          updateHtmlTemplate(_data.id, _data).then(response => {
            if (response.success) {
              this.dialogVisible = false
              this.getList()
              this.notify('更新成功')
            } else {
              this.$message.error('更新失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('更新失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
        case 'delete':
          deleteHtmlTemplate(_data.id).then(response => {
            if (response.success) {
              this.dialogVisible = false
              this.getList()
              this.notify('删除成功')
            } else {
              this.$message.error('删除失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('删除失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handlePageChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleSearch() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSort(v) {
      // 排序功能暂不实现
      console.log('排序:', v)
    },
    handleSetDefault(row) {
      this.$confirm('确认要将此模板设为默认模板吗？', '设置默认模板', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        const data = Object.assign({}, row)
        data.is_default = true
        updateHtmlTemplate(data.id, data).then(response => {
          if (response.success) {
            this.getList()
            this.notify('设置默认模板成功')
          } else {
            this.$message.error('设置失败：' + response.msg)
          }
        }).catch(err => {
          this.$message.error('设置失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
        })
      })
    },
    handlePreviewTemplate(row) {
      this.previewTemplate = row
      this.generateTemplatePreview(row)
      this.previewVisible = true
    },
    generateTemplatePreview(template) {
      let html = template.html_content || '<html><body><h1>暂无模板内容</h1></body></html>'

      // 如果有CSS样式，添加到head中
      if (template.css_content) {
        if (html.toLowerCase().includes('<head>')) {
          html = html.replace(/<\/head>/i, '<style>' + template.css_content + '</style><' + '/head>')
        } else {
          html = '<html><head><style>' + template.css_content + '</style></head><body>' + html + '</body></html>'
        }
      }

      // 如果有JavaScript，添加到body末尾
      if (template.js_content) {
        if (html.toLowerCase().includes('</body>')) {
          html = html.replace(/<\/body>/i, '<script>' + template.js_content + '<' + '/script><' + '/body>')
        } else {
          html = html + '<script>' + template.js_content + '<' + '/script>'
        }
      }

      this.previewHtml = html
    },
    openFullTemplatePreview() {
      this.previewVisible = false
      this.fullPreviewVisible = true
    },
    previewCurrentTemplate() {
      if (!this.temp.html_content) {
        this.$message.warning('请先输入HTML模板内容')
        return
      }

      // 创建临时预览对象
      const tempTemplate = {
        name: this.temp.name || '预览模板',
        template_type: this.temp.template_type,
        html_content: this.temp.html_content,
        css_content: this.temp.css_content,
        js_content: this.temp.js_content
      }

      this.previewTemplate = tempTemplate
      this.generateTemplatePreview(tempTemplate)
      this.previewVisible = true
    },
    getTemplateTypeText(type) {
      const typeMap = {
        'landing_page': '落地页',
        'product_page': '产品页',
        'common': '通用页',
        'layout': '布局',
        'component': '组件'
      }
      return typeMap[type] || '未知'
    },
    getTemplateTypeColor(type) {
      const colorMap = {
        'landing_page': 'success',
        'product_page': 'primary',
        'common': 'info',
        'layout': 'warning',
        'component': 'danger'
      }
      return colorMap[type] || 'info'
    }
  }
}
</script>

<style scoped>
.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.site-info {
  display: flex;
  align-items: center;
}

.search-filter {
  display: flex;
  align-items: center;
  flex: 1;
  justify-content: center;
}

.input-with-select {
  width: 300px;
}

.add-btn {
  width: 120px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-dialog {
  margin: 88px auto !important;
}

/* 预览相关样式 */
.preview-container {
  height: 100%;
}

.preview-header {
  padding: 10px 0;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 15px;
}

.preview-iframe-container {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.full-preview-dialog >>> .el-dialog__body {
  padding: 10px 20px;
}

.full-preview-container {
  width: 100%;
  height: 100%;
}
</style>

